import Vue from 'vue'
import Vuex from 'vuex'
import {getImage} from '../api/book.js'
import QQMapWX from '../static/js/qqmap-wx-jssdk.min.js'

Vue.use(Vuex)
// getImage().then(res=>{
// 	console.log(res)
// })
const getDefaultState = () => {
  return {
  	address:'',
  	image:''
  	// type:[]
  }
}

const state = getDefaultState()

const mutations = {
	SET_IMAGE: (state, image)=>{
		console.log("SET_IMAGE"+image)
		state.image = image
	},
	SET_ADDRESS: (state, address) => {
	  state.address = address
	}
}

const actions = {
	getCitys({commit}){
		// 检测用户是否授权
		// uniapp api中查询authorize查看更多权限
		// 在manifest.json中填写授权提示信息，并填写小程序的appID
		uni.authorize({
			// 所要授权的权限
			scope:"scope.userLocation",
			success() {
				uni.showLoading({
					title:"请稍后"
				})
				console.log("ok")
				// uni 获取当前定位坐标
				uni.getLocation({
				    type: 'gcj02',
				    success: function (res) {
						const qqmapsdk = new QQMapWX({
						            key: 'VNEBZ-WCVWP-LJWDO-VRNQ6-OM6AZ-YLF2J'
						        });
				        // console.log('当前位置的经度：' + res.longitude);
				        // console.log('当前位置的纬度：' + res.latitude);
						
						qqmapsdk.reverseGeocoder({
									location: {
									  latitude: res.latitude,
									  longitude: res.longitude
									},
									
						            success: function (res) {
						                // console.log(res.result.address_component.city);
										commit('SET_ADDRESS',res.result.address_component.city)
										uni.hideLoading()
										getImage(
											{
												key:'fd222fe687e3a416c0e6161449fac2f8',
												catalog_id:'1',
											}).then(response => {
												let array = response.data.result.data;
												let imgs = []
												array.map((arr)=>{
													// console.log(arr)
													imgs.push(arr.img);
												})
											// console.log(imgs)
											commit('SET_IMAGE',imgs[4])
										  resolve()
										}).catch(error => {
										  reject(error)
										})
										
						            },
						   //          fail: function (res) {
						   //              console.log(res);
						   //          },
									// complete: function (res) {
									// 	console.log(res);
									// },
									})
				    }
				});
			},
			fail(res) {
				// console.log(res)
				uni.showToast({
					icon: "none",
				    title: '需要获取您的地址信息，否则部分功能无法使用',
				    duration: 2000
				});
			}
		})
		
	},
	
	
}

const getters = {
	image : state => {
		console.log("getter"+state.image)
		state.image
	}
}

const store = new Vuex.Store({
	state,
	mutations,
	actions,
	getters
})

export default store


